#include "init.h"
#include "power_manager.h"

void pm_dcin_handle_100ms(void)
{
    static bool dcin_pre_status;
    
    if (dcin_pre_status && !POWER_IS_DCIN_OK()) {
        event_set_ui(EVENT_UI_DCIN_OUT);
        dcin_pre_status = false;
    } else if (!dcin_pre_status && POWER_IS_DCIN_OK()) {
        event_set_ui(EVENT_UI_DCIN_IN);
        dcin_pre_status = true;
    }
}

void pm_handle_busy_loop(void)
{
    uint8_t pm_mode;    /* 0, 3uA; 1, 30uA; 2, batlow 30uA */
    uint8_t wakeup_reason = 0;
    
    enum pm_mode_num {
        POWER_3uA_MODE = 0,
        POWER_30uA_MODE,
        POWER_OC_MODE,
        POWER_BATLOW_MODE,
    };
    /* normal 3uA or normal 30uA */
    pm_mode = CONFIG_POWER_LPM_MODE;

    if (event_get_sys_mask() & EVENT_SYS_ABNORMAL) {
        /* it's time to stop to save power */
        event_clear_all();

        if (pm_mode != POWER_3uA_MODE) {

            debug_print("stop...", 0);
            power_prepare_stop();
            wakeup_reason = power_enter_stop();
            
            init();

            event_clear_all();
        } else {
            if (POWER_IS_DCIN_OK()) {
                event_clear_all();
                return;
            }

            debug_print("sleep...\n", 0);
            SYS_DEEP_ENABLE();
            while (1);
        }
    }
}